import { is } from '@electron-toolkit/utils'
import { dirname, join, resolve } from 'path'
import fs from 'fs'
import log from './helper/log'
import { CronJob } from 'cron'
import nodeDiskInfo from 'node-disk-info'
import { app } from 'electron'
import { ShareWindow } from './helper/shareWindow/ShareWindow'

export class Init {
  static config: any = null
  static diskInfo: any = null

  static loadConfig = () => {
    let configPath: string
    if (is.dev) {
      configPath = resolve('config/config.json')
    } else {
      const appPath = process.resourcesPath
      configPath = join(appPath, 'config', 'config.json')
    }
    try {
      const strFile = fs.readFileSync(resolve(configPath), 'utf-8')
      this.config = JSON.parse(strFile)
      log.log('获取的配置信息为:', strFile)
    } catch (e) {
      console.log(e)
    }
  }

  static {
    log.log('主进程初始化中....')
    this.loadConfig()
    this.getDiskInfo()
    this.startShareWindow()
  }

  static async startShareWindow() {
    const startShare = this.config['share_window_setting']['auto_start']
    log.log(`start 共享屏幕：${startShare}`)
    if (!startShare) {
      return
    }
    const GRPC_IP = this.config['share_window_setting'].GRPC_IP
    await ShareWindow.listenEvents(GRPC_IP)
  }




  static getDiskInfo() {
    const homeDir = dirname(app.getPath('home')).slice(0, 2)
    const job = new CronJob('*/30 * * * * *', async () => {
      const disks = await nodeDiskInfo.getDiskInfo()
      const disk = disks.filter(item => item.mounted === homeDir)[0]
      log.log('执行定时任务，获取磁盘信息')
      this.diskInfo = {
        homeDir,
        used: Number.parseInt(((disk.blocks - disk.available) / 1024 / 1024 / 1024).toFixed(0)),
        total: Number.parseInt((disk.blocks / 1024 / 1024 / 1024).toFixed(0))
      }
    })
    job.start()
  }
}
